import React, { FC, MouseEvent } from 'react'
import { Spin } from 'antd'
import { useDispatch } from 'react-redux'
import classNames from 'classnames'
import styles from './EditCanvas.module.scss'
import useGetComponentsInfo from '../../../hooks/useGetComponentsInfo'
import {
  ComponentInfoType,
  changeSelectedId,
  moveComponent,
} from '../../../store/componentsReducer'

import { getComponentConfByType, ComponentConfType } from '../../../components/QuestionComponents'

// * 拖拽组件
import SortableContainer from '../../../components/DragSortable/SortableContainer'
import SortableItem from '../../../components/DragSortable/SortableItem'

type PropsType = {
  loading: boolean
}

// 获取组件类型
function getComponent(componentInfo: ComponentInfoType) {
  const { type, props } = componentInfo

  // 获得组件类型
  const componentConf = getComponentConfByType(type) as ComponentConfType
  if (componentConf === null) return null

  const { Component } = componentConf
  return <Component {...props} />
}

const EditCanvas: FC<PropsType> = ({ loading }) => {
  const { componentList, selectedId } = useGetComponentsInfo()

  const dispatch = useDispatch()
  // 点击保存id
  function handleClick(event: MouseEvent, id: string) {
    event.stopPropagation() //阻止冒泡
    dispatch(changeSelectedId(id))
  }

  if (loading) {
    return (
      <div style={{ textAlign: 'center', marginTop: '24px' }}>
        <Spin />
      </div>
    )
  }

  // ! SortableContainer组件的items属性,需要每个item都有id
  const componentListWidthId = componentList.map(c => {
    return {
      ...c,
      id: c.fe_id,
    }
  })

  // *拖拽排序结束
  function handleDragEnd(oldIndex: number, newIndex: number) {
    dispatch(moveComponent({ oldIndex, newIndex }))
  }

  return (
    <SortableContainer items={componentListWidthId} onDragEnd={handleDragEnd}>
      <div className={styles.canvas}>
        {componentList
          .filter(item => !item.isHidden)
          .map(c => {
            const { fe_id, isLocked, isHidden } = c

            //* 拼接class name
            const wrapperDefaultClassName = styles['component-wrapper']
            const selectedClassName = styles.selected
            const lockedClassName = styles.locked
            const wrapperClassName = classNames({
              [wrapperDefaultClassName]: true,
              [selectedClassName]: fe_id === selectedId,
              [lockedClassName]: isLocked,
            })

            return (
              <SortableItem key={fe_id} id={fe_id}>
                <div className={wrapperClassName} onClick={e => handleClick(e, fe_id)}>
                  <div className={styles.component}>{getComponent(c)}</div>
                </div>
              </SortableItem>
            )
          })}
      </div>
    </SortableContainer>
  )
}

export default EditCanvas
